package com.jstyle.jclife.activity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;



import com.jstyle.blesdk.cmdenum.SendCmdState;
import com.jstyle.blesdk.constant.DeviceKey;
import com.jstyle.jclife.R;


import com.jstyle.jclife.utils.Utils;
import com.otaliastudios.cameraview.CameraListener;
import com.otaliastudios.cameraview.CameraUtils;
import com.otaliastudios.cameraview.CameraView;



import org.reactivestreams.Subscription;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.Map;


import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


public class CameraActivity extends BaseActivity {
    private static final String TAG = "CameraActivity";
    @BindView(R.id.camera)
    CameraView camera;
    @BindView(R.id.bt_change)
    ImageView btChange;
    @BindView(R.id.iv_preview)
    ImageView ivPreview;
    private Subscription subscription;
    private String device_id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        ButterKnife.bind(this);
       // requestPermissions();
        sendData(SendCmdState.Enter_Carmera);

        camera.addCameraListener(new CameraListener() {
            @Override
            public void onPictureTaken(byte[] jpeg) {
                super.onPictureTaken(jpeg);
                CameraUtils.decodeBitmap(jpeg, new CameraUtils.BitmapCallback() {
                    @Override
                    public void onBitmapReady(Bitmap bitmap) {
                        ivPreview.setImageBitmap(bitmap);
                        savePicture(bitmap);
                    }
                });
            }
        });
//        camera.addCameraListener(new CameraListener() {
//            @Override
//            public void onPictureTaken(PictureResult result) {
//                super.onPictureTaken(result);
//                CameraUtils.decodeBitmap(result.getData(), new BitmapCallback() {
//                    @Override
//                    public void onBitmapReady(Bitmap bitmap) {
//
//                    }
//                });
//            }
//        });
//        camera.addCameraListener(new CameraListener() {
//            @Override
//            public void onPictureTaken(byte[] jpeg) {
//                super.onPictureTaken(jpeg);
//                CameraUtils.decodeBitmap(jpeg, new CameraUtils.BitmapCallback() {
//                    @Override
//                    public void onBitmapReady(Bitmap bitmap) {
//
//                    }
//                });
//            }
//        });


    }





    @Override
    public void dataCallback(Map<String, String> maps, SendCmdState sendCmdState) {
        super.dataCallback(maps, sendCmdState);
        switch (sendCmdState){
            case Function:
                String cameraString=maps.get(DeviceKey.KFunction_Carmra);
                if(cameraString!=null&&isFinish){
                    camera.capturePicture();
//                    camera.captureImage(new CameraKitView.ImageCallback() {
//                        @Override
//                        public void onImage(CameraKitView cameraKitView, byte[] bytes) {
////                            Bitmap result = BitmapFactory.decodeByteArray(bytes,0,bytes.length);
////
//                            savePicture(bytes);
//                        }
//                    });

                    isFinish = false;
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        camera.destroy();
        disEnableDeviceCamera();
        unsubscribe();
    }

    private void disEnableDeviceCamera() {
            sendData(SendCmdState.Back_HOME);
           // HomeActivity.mDevice.sendData(SendData.enableCamera(false));

    }

    private void unsubscribe() {
//        if (subscription != null && !subscription.isUnsubscribed()) {
//            subscription.unsubscribe();
//        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //camera.resume();
    }

    @Override
    protected void onStart() {
        super.onStart();
       camera.start();
    }

    boolean isFinish = true;

    @Override
    protected void onPause() {
       // camera.pause();

        super.onPause();
    }

    @Override
    protected void onStop() {
        camera.stop();

        super.onStop();
    }



    private int getZoomScale(String strImgPath) {
        int scale = 1;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(strImgPath, options);
        while (options.outWidth / scale >= ivPreview.getWidth()
                || options.outHeight / scale >= ivPreview.getHeight()) {
            scale *= 2;
        }
        return scale;
    }

    //int type = CameraKit.FACING_BACK;

    @OnClick({R.id.bt_cancel,R.id.bt_change, R.id.iv_camera_start})
    public void onViewClicked(View view) {
        if(Utils.isFastClick()){return;}
        switch (view.getId()) {
            case R.id.iv_camera_start:
                Log.i(TAG, "onViewClicked: ");
                if (isFinish) {
                    camera.capturePicture();
                    isFinish = false;
                }
                break;
            case R.id.bt_change:
                Log.i(TAG, "onViewClicked: change");
               // type = type == CameraKit.FACING_BACK ? CameraKit.FACING_FRONT : CameraKit.FACING_BACK;
                camera.toggleFacing();
                break;
            case R.id.bt_cancel:
                finish();
                break;
        }


    }

    private void savePicture(final Bitmap bitmap) {

        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {


                String path = "";
                try {
                    String fileName = new Date().getTime() + ".jpg";
                    path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/DCIM/Camera" + File.separator + fileName;
                    FileOutputStream fileOutputStream = new FileOutputStream(path);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fileOutputStream);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                emitter.onNext(path);
            }



        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(String path) {
                isFinish = true;
              //  ivPreview.setImageBitmap(result);
                MediaScannerConnection.scanFile(CameraActivity.this,new String[]{path}, null, null);
                Log.i(TAG, "onNext: ");
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

}
